//
//  NSString+WY_Extension.m
//  WYBasisKit
//
//  Created by jacke-xu on 17/2/12.
//  Copyright © 2017年 com.jacke-xu. All rights reserved.
//

#import "NSString+WY_Extension.h"
//#import "WY_BoolJudge.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <sys/utsname.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
//#import "GTMBase64.h"

static NSString *const randomString = @"二十丁厂七卜人入八九几儿了力乃刀又三于干亏士工土才寸下大丈与万上小口巾山千乞川亿个勺久凡及夕丸么广亡门义之尸弓己已子卫也女飞刃习叉马乡丰王井开夫天无元专云扎艺木五支厅不太犬区历尤友匹车巨牙屯比互切瓦止少日中冈贝内水见午牛手毛气升长仁什片仆化仇币仍仅斤爪反介父从今凶分乏公仓月氏勿欠风丹匀乌凤勾文六方火为斗忆订计户认心尺引丑巴孔队办以允予劝双书幻的一了是我不在人们有来他这上着个地到大里说去子得也和那要下看天时过出小么起你都把好还多没为又可家学只以主会样年想能生同老中从自面前头到它后然走很像见两用她国动进成回什边作对开而已些现山民候经发工向事命给长水几义三声于高正妈手知理眼志点心战二问但身方实吃做叫当住听革打呢真党全才四已所敌之最光产情路分总条白话东席次亲如被花口放儿常西气五第使写军吧文运在果怎定许快明行因别飞外树物活部门无往船望新带队先力完间却站代员机更九您每风级跟笑啊孩万少直意夜比阶连车重便斗马哪化太指变社似士者干石满决百原拿群究各六本思解立河爸村八难早论吗根共让相研今其书坐接应关信觉死步反处记将千找争领或师结块跑谁草越字加脚紧爱等习阵怕月青半火法题建赶位唱海七女任件感准张团屋爷离色脸片科倒睛利世病刚且由送切星晚表够整认响雪流未场该并底深刻平伟忙提确近亮轻讲农古黑告界拉名呀土清阳照办史改历转画造嘴此治北必服雨穿父内识验传业菜爬睡兴";

@implementation NSString (WY_Extension)

/** 获取手机号运营商 */
//+ (NSString *)wy_mobilePhoneOperators:(NSString *)string {
//    
//    return [WY_BoolJudge wy_isMobilePperators:string] ? @"中国移动": ([WY_BoolJudge wy_isUnicomPperators:string] ? @"中国联通": ([WY_BoolJudge wy_isTelecomPperators:string] ? @"中国电信": @"未知"));
//}
/** 获取手机号 */
+ (NSString *)wy_mobilePhoneNumber{
    NSString *number = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];
    
    return number;
}

/** 返回一个计算好的字符串的高度和宽度 */
- (CGSize)wy_boundingRectWithSize:(CGSize)size withFont:(UIFont *)font lineSpacing:(CGFloat)lineSpacing {

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:lineSpacing];
    NSDictionary *attribute = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle};
    
    CGSize retSize = [self boundingRectWithSize:size
                                        options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                     attributes:attribute
                                        context:nil].size;
    
    return retSize;
}

/** 计算显示文本需要几行 */
- (CGFloat)wy_textShowLinesWithControlWidth:(CGFloat)controlWidth font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing {
    
    //计算总高度
    CGFloat totalHeight = [self wy_boundingRectWithSize:CGSizeMake(controlWidth, 0) withFont:font lineSpacing:lineSpacing].height;
    
    //计算每行的高度
    CGFloat lineHeight = font.lineHeight+lineSpacing;
    
    return totalHeight/lineHeight;
}

/** 计算显示文本到指定行数时需要的高度 */
- (CGFloat)wy_textHeightWithSpecifyRow:(NSInteger)specifyRow font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing {
    
    return (font.lineHeight+lineSpacing)*specifyRow;
}

/** 将中文转换成UTF8编码格式 */
+ (NSString *)wy_UTF8StrFromChinese:(NSString *)chineseStr {
    
    return [chineseStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

/** 将UTF8编码解码 */
+ (NSString *)wy_chineseStrFromUTF8Str:(NSString *)UTF8Str {
    
    return [UTF8Str stringByRemovingPercentEncoding];
}





/** 时间戳转星座
 
 摩羯座 12月22日------1月19日
 水瓶座 1月20日-------2月18日
 双鱼座 2月19日-------3月20日
 白羊座 3月21日-------4月19日
 金牛座 4月20日-------5月20日
 双子座 5月21日-------6月21日
 巨蟹座 6月22日-------7月22日
 狮子座 7月23日-------8月22日
 处女座 8月23日-------9月22日
 天秤座 9月23日------10月23日
 天蝎座 10月24日-----11月21日
 射手座 11月22日-----12月21日
 
 */
//+ (NSString *)wy_timestampToConstellation:(NSString *)timerSp {
//    
//    //计算月份
//    NSString *date = [self wy_convertToDate:timerSp];
//    NSString *retStr=@"";
//    NSString *birthStr = [date substringFromIndex:5];
//    int month=0;
//    NSString *theMonth = [birthStr substringToIndex:2];
//    if([[theMonth substringToIndex:0] isEqualToString:@"0"]){
//        month = [[theMonth substringFromIndex:1] intValue];
//    }else{
//        month = [theMonth intValue];
//    }
//    //计算天数
//    int day=0;
//    NSString *theDay = [birthStr substringFromIndex:3];
//    if([[theDay substringToIndex:0] isEqualToString:@"0"]){
//        day = [[theDay substringFromIndex:1] intValue];
//    }else {
//        day = [theDay intValue];
//    }
//    
//    if (month<1 || month>12 || day<1 || day>31){
//        return @"错误日期格式!";
//    }
//    if(month==2 && day>29) {
//        return @"错误日期格式!!";
//    }else if(month==4 || month==6 || month==9 || month==11) {
//        if (day>30) {
//            return @"错误日期格式!!!";
//        }
//    }
//    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
//    NSString *astroFormat = @"102123444543";
//    retStr=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(month*2-(day < [[astroFormat substringWithRange:NSMakeRange((month-1), 1)] intValue] - (-19))*2,2)]];
//    return [NSString stringWithFormat:@"%@座",retStr];
//}
//
///** 根据时间戳算年龄 */
//+ (NSString *)wy_timestampToAge:(NSString *)timerSp {
//    
//    NSString *dateString = [self wy_convertToDate:timerSp];
//    NSString *year = [dateString substringWithRange:NSMakeRange(0, 4)];
//    NSString *month = [dateString substringWithRange:NSMakeRange(5, 2)];
//    NSString *day = [dateString substringWithRange:NSMakeRange(dateString.length-2, 2)];
//    NSDate *nowDate = [NSDate date];
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
//    NSDateComponents *compomemts = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay fromDate:nowDate];
//    NSInteger nowYear = compomemts.year;
//    NSInteger nowMonth = compomemts.month;
//    NSInteger nowDay = compomemts.day;
//    
//    // 计算年龄
//    NSInteger userAge = nowYear - year.intValue - 1;
//    if ((nowMonth > month.intValue) || (nowMonth == month.intValue && nowDay >= day.intValue)) {
//        userAge++;
//    }
//    return [NSString stringWithFormat:@"%ld",(long)userAge];
//}

/** 获取手机时间戳 */
+ (NSString *)wy_getCurrentTimeSp {
    
    NSDate *date = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    
    return timeSp;
}

/** 获取网络时间戳*/
+ (NSString *)wy_getNetworkTimeSp {
    
    NSString *urlString = @"http://m.baidu.com";
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
#pragma clang diagnostic pop
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
#pragma clang diagnostic pop
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    return [NSString stringWithFormat:@"%ld", (long)[netDate timeIntervalSince1970]];
}

/** 图片转字符串 */
+ (NSString *)wy_UIImageToBase64Str:(UIImage *)image {
    
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    return encodedImageStr;
}

/** 去除字符串中的空格 */
+ (NSString *)wy_wipeSpaceFromStr:(NSString *)str {
    
    NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
    NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
    NSArray *parts = [str componentsSeparatedByCharactersInSet:whitespaces];//在空格处将字符串分割成一个 NSArray
    NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];//去除空串
    NSString *jointStr  = @"";
    str = [filteredArray componentsJoinedByString:jointStr];
    
    return str;
}

/** 去除字符串两端的空格 */
+ (NSString *)wy_wipeBothEndsSpaceFromStr:(NSString *)str {
    
    NSString *s = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];//该方法是去掉两端的空格
    
    //NSString *s =  [s stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];//该方法也可以
    
    return s;
}

/** 去除字符串中的特定符号 */
+ (NSString *)wy_wipeAppointSymbolFromStr:(NSString *)str AppointSymbol:(NSString *)appointSymbol WithStr:(NSString *)replacement {
    
    NSString *b = [str stringByReplacingOccurrencesOfString:appointSymbol withString:replacement];//该方法是去掉指定符号
    return b;
}

/** 获取设备ip地址*/
+ (NSString *)wy_getDeviceIpAddress {
    
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}

/** 返回一个包含匹配正则表达式的新字符串替换为模版字符串 */
+ (NSString *)wy_stringByReplacingRegex:(NSString *)regex
                             options:(NSRegularExpressionOptions)options
                          withString:(NSString *)replacement content:(NSString *)string {
    
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
    if (!pattern) return string;
    return [pattern stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:replacement];
}

/** 匹配正则表达式，并使用匹配的每个对象执行给定的块 */
+ (void)wy_enumerateRegexMatches:(NSString *)regex
                      options:(NSRegularExpressionOptions)options
                   usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block content:(NSString *)string {
    
    if (regex.length == 0 || !block) return;
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
    if (!regex) return;
    [pattern enumerateMatchesInString:string options:kNilOptions range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        block([string substringWithRange:result.range], result.range, stop);
    }];
}

/** 根据银行卡号获取所属银行 */
+ (NSString *)wy_getBankName:(NSString *)string {
    
    if(string==nil || string.length<16 || string.length>19){
        NSLog(@"传入的银行卡号不合法");
        return @"";
    }
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"bank" ofType:@"plist"];
    NSDictionary* resultDic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    NSArray *bankBin = resultDic.allKeys;
    
    //6位Bin号
    NSString *cardbin_6 = [string substringWithRange:NSMakeRange(0, 6)];
    //8位Bin号
    NSString *cardbin_8 = [string substringWithRange:NSMakeRange(0, 8)];
    
    if ([bankBin containsObject:cardbin_6]) {
        return [resultDic objectForKey:cardbin_6];
    }else if ([bankBin containsObject:cardbin_8]){
        return [resultDic objectForKey:cardbin_8];
    }else{
        NSLog(@"plist文件中不存在请自行添加对应卡种");
        return @"";
    }
    return @"";
}
+ (NSString *)deviceModel{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    return deviceString;
}
/**
 获取苹果设备型号
 */
+ (NSString *)wy_appleDiviceType {
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
}

+ (NSString *)wy_spacingBankCardNumber:(NSString *)bankCardNumber {
    
    NSString *tmpStr = bankCardNumber;
    NSInteger size = (tmpStr.length / 4);
    NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init];
    for (int n = 0;n < size; n++)
    {
        [tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(n*4, 4)]];
    }
    
    [tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(size*4, (tmpStr.length % 4))]];
    
    tmpStr = [tmpStrArr componentsJoinedByString:@" "];
    
    return tmpStr;
}

+ (NSString *)wy_bankCardNumberRemoveSpacing:(NSString *)bankCardNumber {
    
    return [bankCardNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
}

+ (NSString *)wy_securityBankCard:(NSString *)bankCardNumber {
    
    NSString *IDCard =  bankCardNumber;
    if(IDCard.length > 10){
        return [NSString stringWithFormat:@"%@********%@",[IDCard substringToIndex:6], [IDCard substringFromIndex:IDCard.length-4]];
    }else if(IDCard.length > 4){
        return [NSString stringWithFormat:@"********%@", [IDCard substringFromIndex:IDCard.length-4]];
    }
    return IDCard;
}

//将 &lt 等类似的字符转化为HTML中的“<”等
+ (NSString *)wy_htmlEntityDecode:(NSString *)string {
    
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"
    
    return string;
}

/** 字符串反转 */
- (NSString *)wy_stringInversion {
    
    NSMutableString *reverString = [NSMutableString stringWithCapacity:self.length];
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [reverString appendString:substring];
    }];
    return reverString;
}

/** 获取汉字的拼音 */
- (NSString *)wy_pinyinTransform:(NSString *)chineseStr {
    
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chineseStr mutableCopy];
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    //返回最近结果
    return pinyin;
}

+ (NSString *)wy_emptyStr:(NSString *)str {
    
    if(([str isKindOfClass:[NSNull class]]) || ([str isEqual:[NSNull null]]) || (str == nil) || (!str)) {
        
        str = @"";
    }
    return str;
}
#pragma mark < ------------- 判断输入是否全是空格 */
- (BOOL)isEmpty{
    
    if(([self isKindOfClass:[NSNull class]]) || ([self isEqual:[NSNull null]]) || (self == nil) || (!self)){
        return false;
    }else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [self stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return false;
        } else {
            return true;
        }
    }
}
/** 普通字符串转十六进制字符串 */
- (NSString *)hexStringFromString{
    NSData *myD = [self dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

/**< 加密方法 */
//- (NSString*)aci_encryptWithAES{
//    return [self aci_encryptWithAES:PSW_AES_KEY];
//}
//
///**< 加密方法 */
//- (NSString*)aci_encryptWithAES:(NSString *)key{
//    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
//    NSData *AESData = [self AES128operation:kCCEncrypt
//                                       data:data
//                                        key:[Util addString:key count:32]
//                                         iv:AES_IV_PARAMETER];
//
//    NSString *baseStr_GTM = [self encodeBase64Data:AESData];
//    //NSString *baseStr = [AESData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//
//    //NSLog(@"*****************\nGTMBase:%@\n*****************", baseStr_GTM);
//    //NSLog(@"*****************\niOSCode:%@\n*****************", baseStr);
//    return baseStr_GTM;
//}
///**< 解密方法 */
//- (NSString*)aci_decryptWithAES{
//    return [self aci_decryptWithAES:PSW_AES_KEY];
//}
///**< 解密方法 */
//- (NSString*)aci_decryptWithAES:(NSString *)key{
//    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
//    NSData *baseData_GTM = [self decodeBase64Data:data];
//
//    NSData *baseData = [[NSData alloc]initWithBase64EncodedString:self options:0];
//
//    NSData *AESData_GTM = [self AES128operation:kCCDecrypt
//                                           data:baseData_GTM
//                                            key:key
//                                             iv:AES_IV_PARAMETER];
//    NSData *AESData = [self AES128operation:kCCDecrypt
//                                       data:baseData
//                                        key:key
//                                         iv:AES_IV_PARAMETER];
//
//    NSString *decStr_GTM = [[NSString alloc] initWithData:AESData_GTM encoding:NSUTF8StringEncoding];
//    NSString *decStr = [[NSString alloc] initWithData:AESData encoding:NSUTF8StringEncoding];
//
//    NSLog(@"*****************\nGTMBase:%@\n*****************", decStr_GTM);
//    NSLog(@"*****************\niOSCode:%@\n*****************", decStr);
//
//    return decStr;
//}
//
///**
// *  AES加解密算法
// *
// *  @param operation kCCEncrypt（加密）kCCDecrypt（解密）
// *  @param data      待操作Data数据
// *  @param key       key
// *  @param iv        向量
// *
// *
// */
//- (NSData *)AES128operation:(CCOperation)operation data:(NSData *)data key:(NSString *)key iv:(NSString *)iv {
//    // key
//    char keyPtr[32 + 1];  //kCCKeySizeAES128是加密位数 可以替换成256位的
//    bzero(keyPtr, sizeof(keyPtr));
//    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
//
//    // IV
//    char ivPtr[kCCBlockSizeAES128 + 1];
//    bzero(ivPtr, sizeof(ivPtr));
//    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
//
//    size_t bufferSize = data.length + kCCBlockSizeAES128;
//    void *buffer = malloc(bufferSize);
//    size_t numBytesEncrypted = 0;
//
//    // 设置加密参数
//    //（根据需求选择什么加密位数128or256，PKCS7Padding补码方式之类的_(:з」∠)_，详细的看下面吧）
//    CCCryptorStatus cryptorStatus = CCCrypt(operation,
//                                            kCCAlgorithmAES,
//                                            kCCOptionPKCS7Padding,
//                                            keyPtr,
//                                            kCCKeySizeAES256,
//                                            ivPtr,
//                                            data.bytes,
//                                            data.length,
//                                            buffer,
//                                            bufferSize,
//                                            &numBytesEncrypted
//                                            );
//
//    if(cryptorStatus == kCCSuccess) {
//        NSLog(@"Success");
//        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
//
//    } else {
//        NSLog(@"Error");
//    }
//
//    free(buffer);
//    return nil;
//}

///**< GTMBase64编码 */
//- (NSString*)encodeBase64Data:(NSData *)data {
//    data = [GTMBase64 encodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
//
///**< GTMBase64解码 */
//- (NSData*)decodeBase64Data:(NSData *)data {
//    data = [GTMBase64 decodeData:data];
//    return data;
//}

- (NSString *)setupBrString{
    NSString *newStr=[self stringByReplacingOccurrencesOfString:@"{br}" withString:@"\n"];
    //去除首尾空格和换行：
    NSString *content = [newStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return content;
}
/// 去除所有空格
- (NSString *)removeSpace{
   
//    NSString *temp = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
//    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
//    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//    return temp;
    NSString *temp = [self stringByReplacingOccurrencesOfString:@" "withString:@""];

    return [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
/// 去除首尾空格
- (NSString *)removeOfSpace{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSURL *)strinWithURL{
    return [NSURL URLWithString:self];
}
/** url转string */
+ (NSString *)urlWithString:(NSURL *)url{
    return url.absoluteString;
}
/** 返回字符串宽度 */
- (CGFloat)jk_width:(CGFloat)font{
    CGSize rect=CGSizeZero;
    rect = [self boundingRectWithSize:CGSizeZero options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return rect.width;
}
/** 返回字符串宽度 */
- (CGFloat)jk_width:(CGFloat)font width:(CGFloat)width{
    CGSize rect=CGSizeZero;
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    rect = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return rect.width;
}
/** 返回字符串高度 */
- (CGFloat)jk_Height:(CGFloat)font width:(CGFloat)width{
    CGSize rect=CGSizeZero;
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    
    rect = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return rect.height;
}
+ (CGFloat)jk_Height:(CGFloat)font width:(CGFloat)width{
    NSString *obj = [[NSString alloc]init];
    return [obj jk_Height:font width:width];
}
/** 返回字符串高度 设置行距*/
- (CGFloat)jk_Height:(CGFloat)font width:(CGFloat)width lineSpacing:(CGFloat)lineSpacing{
    CGSize rect=CGSizeZero;
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    
    //调整行距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    
    rect = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font],NSParagraphStyleAttributeName:paragraphStyle} context:nil].size;
    return rect.height+1;
}

- (NSString *)htmlToString{
    NSDictionary* options = @{
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
        NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)
    };
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSAttributedString *att = [[NSAttributedString alloc]initWithData:data options:options documentAttributes:nil error:nil];
    return att.string;
}

/**
 * 返回H5标签转义属性
 */
- (NSString*)htmlText{
    if ([self isEmpty]) {
        NSDictionary* options = @{
                                  NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
                                  };
        NSMutableAttributedString *attrs = [[NSMutableAttributedString alloc] initWithData:[self dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
        NSString *html = [attrs.string stringByReplacingOccurrencesOfString:@"&nbsp" withString:@" "];
        return html;
    }
    return @"";
}

/** 超文本HTML格式转换为富文本AtrributeString格式*/
- (NSAttributedString *)attributeStringByHtmlString{
    NSAttributedString *attributeString;
    NSData *htmlData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                   NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]
                                   };
    NSError *error = nil;
    attributeString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];
    return attributeString;
}
/** html转字符串 */
-(NSString *)filterHTMLString{
    NSString *html = self;
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * message = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&message];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",message] withString:@""];
    }
    return html;
}

/*
 html = [html stringByReplacingOccurrencesOfString:@"&nbsp" withString:@" "];
    html = [html stringByReplacingOccurrencesOfString:@"&mdash" withString:@"—"];
    html = [html stringByReplacingOccurrencesOfString:@"&quot" withString:@"\""];
    html = [html stringByReplacingOccurrencesOfString:@"&hellip" withString:@"..."];
    html = [html stringByReplacingOccurrencesOfString:@"&rdquo" withString:@"”"];
    html = [html stringByReplacingOccurrencesOfString:@"&lsquo" withString:@"‘"];
    html = [html stringByReplacingOccurrencesOfString:@"&rsquo" withString:@"’"];
    html = [html stringByReplacingOccurrencesOfString:@"&ldquo" withString:@"“"];
    html = [html stringByReplacingOccurrencesOfString:@"&darr" withString:@"↓"];
    html = [html stringByReplacingOccurrencesOfString:@"&middot" withString
 */
/// 提取字符串中的数字
- (NSString *)getNumberFromStr{
    NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    return[[self componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}

//浮点数去掉小数点之后的0
- (NSString*)removeFloatAllZero{
    
//    /*---------第一种方法-----------*/
//    NSString * testNumber = string;
//    NSString * s = nil;
//    NSInteger offset = testNumber.length - 1;
//
//    while (offset){
//        s = [testNumber substringWithRange:NSMakeRange(offset, 1)];
//        if ([s isEqualToString:@"0"] || [s isEqualToString:@"."]){
//            offset--;
//        }else{
//            break;
//        }
//    }
//    NSString * outNumber = [testNumber substringToIndex:offset+1];
//    NSLog(@"%@", outNumber);
    
    
    /*---------第二种方法-----------*/
    NSString * testNumber = self;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    return outNumber;
}

/// 数字：阿拉伯转小写
+ (NSString *)numberStyle:(NSInteger)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    /// 拼写输出中文
    formatter.numberStyle = NSNumberFormatterSpellOutStyle;
    /// 如果不设置locle 跟随系统语言
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    NSString *spellOutStr = [formatter stringFromNumber:[NSNumber numberWithDouble: number]];
    return spellOutStr;
}

/**
 生成随机字母
 @param number  需要的个数
 @return 生成的字符串
 */
+ (NSString *)randomString:(NSInteger)number{
    
    NSString *ramdom;
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 1; i ; i ++) {
        int a = (arc4random() % 122);
        if (a > 96) {
            char c = (char)a;
            [array addObject:[NSString stringWithFormat:@"%c",c]];
            if (array.count == number) {
                break;
            }
        } else continue;
    }
    ramdom = [array componentsJoinedByString:@""];
    return ramdom;
}
/// 获取随机中文字符串
+ (NSString *)randomString{
    NSInteger length = (arc4random() % 7)+3;
    NSMutableString *string = [NSMutableString string];
    for (int i=0; i<length; i++) {
        int num = (arc4random() % randomString.length);
        unichar str = [randomString characterAtIndex:num];
        [string appendString:[NSString stringWithFormat:@"%C",str]];
    }
    return string;
}
/// 获取随机中文字符串- max: 最大不超过的个数
+ (NSString *)randomStringMax:(NSInteger)max{
    NSInteger length = (arc4random() % max)+1;
    NSMutableString *string = [NSMutableString string];
    for (int i=0; i<length; i++) {
        int num = (arc4random() % randomString.length);
        unichar str = [randomString characterAtIndex:num];
        [string appendString:[NSString stringWithFormat:@"%C",str]];
    }
    return string;
}

//判断是否为整形：
- (BOOL)isPureInt{
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
//判断是否为浮点形：
- (BOOL)isPureFloat{
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}
//判断是否是纯数字
- (BOOL)isNumberValue{
    return ([self isPureInt] || [self isPureFloat]);
}
//判断是否是纯数字
- (BOOL)regexMatchesOnlyNumber:(NSString *)string{
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9.]+$"];
    BOOL isMatch = [test evaluateWithObject:string];
    return isMatch;
}
///设置最大小数位
- (NSString *)number:(int)num{
    if ([self isNumberValue]) {
        NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [formatter setMaximumFractionDigits:num];
        //[formatter setMinimumFractionDigits:1];
        formatter.groupingSize = 20;
        //[formatter setLocale:[NSLocale currentLocale]];
        //NSString *myString = [formatter stringFromNumber:[NSNumber numberWithFloat:123.456]];
        
        return [formatter stringFromNumber:[NSDecimalNumber decimalNumberWithString:self]];
    }else{
        return self;
    }
}

- (NSString *)number{
    if ([self isNumberValue]) {
        NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [formatter setMaximumFractionDigits:1];
        [formatter setMinimumFractionDigits:1];
        formatter.groupingSize = 20;
        //[formatter setLocale:[NSLocale currentLocale]];
        //NSString *myString = [formatter stringFromNumber:[NSNumber numberWithFloat:123.456]];
        
        return [formatter stringFromNumber:[NSDecimalNumber decimalNumberWithString:self]];
    }else{
        return self;
    }
}
- (NSString *)number2{
    if ([self isNumberValue]) {
        NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [formatter setMaximumFractionDigits:2];
        [formatter setMinimumFractionDigits:2];
        formatter.groupingSize = 20;
        //[formatter setLocale:[NSLocale currentLocale]];
        //[NSDecimalNumber decimalNumberWithString:self]
        //[NSNumber numberWithDouble:[self doubleValue]]
        return [formatter stringFromNumber:[NSDecimalNumber decimalNumberWithString:self]];
    }else{
        return self;
    }
}
#pragma mark - 判断字符串是否包含数字
- (BOOL)isStringContainNumber{
    NSRegularExpression *numberRegular = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSInteger count = [numberRegular numberOfMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
    //count是str中包含[0-9]数字的个数，只要count>0，说明str中包含数字
    if (count > 0) {
        return YES;
    }
    return NO;
}
#pragma mark - 判断是否是字母
- (BOOL)isABC{
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];

    if(tLetterMatchCount>=1){
        return YES;
    }else{
        return NO;
    }
}

- (NSString *)fenToYuan{
    NSDecimalNumber *yuan;
    if ([self isEqualToString:@""]) {
        return @"";
    }else{
        yuan = [NSDecimalNumber decimalNumberWithString:self];
    }
    if (self) {
        // 除以 100
        //NSDecimalNumber *fen = [NSDecimalNumber decimalNumberWithMantissa:[self integerValue] exponent:-2 isNegative:NO];
        NSDecimalNumber *fen = [yuan decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"100"]];
        return fen.stringValue;
    }
    return @"";
}

- (NSString *)yuanToFen{
    NSDecimalNumber *fen;
    if ([self isEqualToString:@""]) {
        return @"";
    }else{
        fen = [NSDecimalNumber decimalNumberWithString:self];
    }
    if (self) {
        // 乘 100
        //NSDecimalNumber *yuan = [NSDecimalNumber decimalNumberWithMantissa:[self integerValue] exponent:2 isNegative:NO];
        NSDecimalNumber *yuan = [fen decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@"100"]];
        return yuan.stringValue;
    }
    return @"";
}

@end
